package cn.jingyuan.owl.json.fastjson.serializable;

import cn.jingyuan.owl.enums.core.EnumInteger;
import cn.jingyuan.owl.enums.core.EnumString;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;

public class ExtendSerializeConfig extends SerializeConfig {

    public static final SerializeConfig INSTANCE = new ExtendSerializeConfig();

    public static SerializeConfig getInstance() {
        return INSTANCE;
    }

    public ObjectSerializer getObjectWriter(Class<?> clazz) {
        ObjectSerializer serializer;

        if (clazz.isEnum()) {
            JSONType jsonType = clazz.getAnnotation(JSONType.class);
            if (null != jsonType) {
                try {
                    Class<?> aClass = jsonType.serializer();
                    serializer = (ObjectSerializer) aClass.newInstance();

                    return serializer;
                } catch (Throwable error) {
                    // skip
                }
            }

            // 判断 classpath 下是否存在 EnumString.class
            if (EnumHelper.existEnumCoreClass()) {
                if (EnumString.class.isAssignableFrom(clazz)) {
                    serializer = EnumStringSerializer.INSTANCE;
                    this.put(clazz, serializer);

                    return serializer;
                }

                if (EnumInteger.class.isAssignableFrom(clazz)) {
                    serializer = EnumIntegerSerializer.INSTANCE;
                    this.put(clazz, serializer);

                    return serializer;
                }
            }
        }

        return super.getObjectWriter(clazz);
    }

}
